package edu.xhu.communityantiepidemicsystemback.controller;

import edu.xhu.communityantiepidemicsystemback.common.result.Result;
import edu.xhu.communityantiepidemicsystemback.dto.UpdatePwd;
import edu.xhu.communityantiepidemicsystemback.entity.Staff;
import edu.xhu.communityantiepidemicsystemback.service.AuthService;
import edu.xhu.communityantiepidemicsystemback.vo.LoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/auth")
@Slf4j
public class AuthController {
    @Autowired
    private AuthService authService;

    @PostMapping("/login")
    public Result<?> login(@RequestBody Staff staff){
        boolean result= authService.checkLoginAccount(staff);
        if(result){
            Staff res=authService.getInfoByAccount(staff.getAccount());
            if(res!=null){
                LoginVO loginVO = LoginVO.builder()
                        .name(res.getName())
                        .id(res.getId())
                        .account(res.getAccount()).build();
                return new Result<>().success().put(loginVO);
            }
            return new Result<>().error("登陆失败");
        }
        return new Result<>().error("登陆失败");
    }

    @GetMapping("/401")
    public Result<?> unauthorized() {
        return new Result<>().error(401,"用户无权限访问");
    }

    @PostMapping("/change")
    public Result modifyPassword(@RequestBody UpdatePwd updatePwd){
        Staff staff=new Staff();
        staff.setAccount(updatePwd.getAccount());
        staff.setPassword(updatePwd.getOldpassword());
        boolean result= authService.checkLoginAccount(staff);
        if(result){
            boolean a=authService.updatePwdByAccount(updatePwd);
            if(a) {
                return new Result<>().success();
            }
            else{
                return new Result<>().error("修改失败");
            }
        }
        return new Result<>().error("修改失败");
    }
}
